﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using XKJ.OAWeb.Dto;
using XKJ.OAWeb.Infrastructrue;
using XKJ.OAWeb.Models;
using XKJ.OAWeb.Shared;

namespace XKJ.OAWeb.Application
{
    public class UserService : IUserService
    {
        IBaseRepository<User> _user;
        IBaseRepository<Role> _role;

        public UserService(IBaseRepository<User> user, IBaseRepository<Role> role)
        {
            _user = user;
            _role = role;
        }

        //登录
        public User Login(User login)
        {
            return _user.Show().Where(x => x.UserName.Equals(login.UserName) && x.UserPassword.Equals(login.UserPassword)).SingleOrDefault();
        }
        //添加
        public int UserAdd(User user)
        {
            user.RId = 0;
            return _user.Add(user);
        }
        //反填
        public User UserBackfill(int Id)
        {
            return _user.Backfill(Id);
        }
        //删除Id
        public bool UserDeleteId(int Id)
        {
            return _user.DeleteId(Id);
        }
        //用户角色显示
        public PageList<UserRoleDto> UserRoleShow(int Pageindex, int Pagesize, string? UserName)
        {
            var list = from a in _user.Show()
                       join b in _role.Show() on a.RId equals b.RId
                       select new UserRoleDto
                       {
                           UId=a.UId,
                           UserName=a.UserName,
                           UserPassword=a.UserPassword,
                           RId=a.RId,
                           RoleName=b.RoleName,
                           Describe=b.Describe,
                           LId=b.LId
                       };

            if (!string .IsNullOrEmpty(UserName))
            {
                list = list.Where(x => x.UserName.Contains(UserName));
            }

            PageList<UserRoleDto> page = new()
            {
                Total = list.Count(),
                Plist = list.Skip((Pageindex - 1) * Pagesize).Take(Pagesize).ToList()
            };

            return page;
        }

        //显示
        public PageList<User> UserShow(int Pageindex, int Pagesize,string? UserName)
        {
            var list = _user.Show().ToList();

            if (!string.IsNullOrEmpty(UserName))
            {
                list = list.Where(x => x.UserName.Contains(UserName)).ToList();
            }

            PageList<User> page = new()
            {
                Total = list.Count(),
                Plist = list.Skip((Pageindex - 1) * Pagesize).Take(Pagesize).ToList()
            };
            return page;
        }
        //修改
        public int UserUptdate(User user)
        {
            return _user.Uptdate(user);
        }
    }
}
